﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Text;
using ZhongJia.Core;

namespace GanQL.Web.Infrastructure.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger _logger;
        private readonly IHostingEnvironment _hostingEnvironment;

        public GlobalExceptionFilter(
            IHostingEnvironment hostingEnvironment,
            ILoggerFactory logger)
        {
            _hostingEnvironment = hostingEnvironment;
            _logger = logger.CreateLogger("exception");
        }

        public void OnException(ExceptionContext context)
        {
            var ex = context.Exception;
            if (ex is UserFriendlyException)
            {
                var userFriendlyException = (UserFriendlyException)ex;
                context.Result = new JsonResult(new
                {
                    successed = false,
                    message = userFriendlyException.Message,
                    Code = userFriendlyException.Code
                });
            }
            else if (ex is UnauthorizedAccessException || ex.InnerException is UnauthorizedAccessException)
            {
                context.Result = new UnauthorizedResult();
            }
            else
            {
                var sbError = new StringBuilder();
                GetStackTraces(ex, sbError);
                this._logger.LogError(sbError.ToString(), context.Exception);
            }
        }

        private void GetStackTraces(Exception ex, StringBuilder sbInfo)
        {
            if (ex != null)
            {
                sbInfo.Append(ex.StackTrace);
                GetStackTraces(ex.InnerException, sbInfo);
            }
        }
    }
}
